package main

import (
	"log"
	"net/http"
	"strconv"
	"xiaoniu-job/internal/client"
	"xiaoniu-job/internal/config"
	"xiaoniu-job/internal/cron"
	"xiaoniu-job/internal/db"
	"xiaoniu-job/internal/executor"
	myLog "xiaoniu-job/internal/log"
	"xiaoniu-job/internal/task"
	"xiaoniu-job/internal/user"
)

func main() {
	// 加载配置
	initConfig := config.InitServerConfig()
	if !initConfig {
		log.Fatalln("App config file read error!")
		return
	}
	// 初始化数据库
	db.InitDb()

	// 删除执行器的所有地址
	db.FlushExecutorAddresses()

	// 后台定时任务
	go cron.Init()
	go cron.DoUpdateTaskCronJob()
	go cron.DoBackGroundJob()

	log.Printf("=======welcome to %s | 菜牛任务调度系统， 监听端口为%d ========\n", config.ServerRation.AppName,
		config.ServerRation.AppPort)

	// 执行器相关接口
	http.HandleFunc("/api/executor/add", executor.AddHandler)
	http.HandleFunc("/api/executor/update", executor.UpdateHandler)
	http.HandleFunc("/api/executor/delete", executor.DeleteHandler)
	http.HandleFunc("/api/executor/list", executor.ListHandler)
	http.HandleFunc("/api/executor/select", executor.SelectHandler)

	// 调度日志接口
	http.HandleFunc("/api/log/list", myLog.ListHandler)

	// 任务相关接口
	http.HandleFunc("/api/task/add", task.AddHandler)
	http.HandleFunc("/api/task/update", task.UpdateHandler)
	http.HandleFunc("/api/task/delete", task.DeleteHandler)
	http.HandleFunc("/api/task/list", task.ListHandler)
	http.HandleFunc("/api/task/select", task.SelectHandler)
	http.HandleFunc("/api/task/runOnce", task.RunOnceHandler)

	// 客户端回调日志接口
	http.HandleFunc("/api/client/callBack", client.CallBackHandler)
	http.HandleFunc("/api/client/queryLocalLog", client.QueryLogHandler)
	http.HandleFunc("/api/client/heartBeat", client.HeartBeatHandler)

	http.HandleFunc("/api/login", user.LoginHandler)

	http.ListenAndServe(":"+strconv.Itoa(config.ServerRation.AppPort), nil)
}
